import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
	HEADERPARAMS,
} from "@/config/app";
import { toLogin, checkLogin } from "../libs/login";
import { useAppStore } from "@/stores/app";

/**
 * 发送请求
 */
function baseRequest(
	url,
	method,
	data,
	{ noAuth = false, noVerify = false },
	params
) {
	const appStore = useAppStore();
	let Url = HTTP_REQUEST_URL,
		header = HEADER;
	if (params != undefined) {
		header = HEADERPARAMS;
		data = params
	}
	// if (!noAuth) {
	// 	//登录过期自动登录
	// 	if (!appStore.token && !checkLogin()) {
	// 		toLogin();
	// 		return Promise.reject({
	// 			msg: '未登录'
	// 		});
	// 	}
	// }
	if (appStore.token) header[TOKENNAME] = appStore.token;
	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + "/api/front/" + url,
			method: method || "GET",
			header: header,
			data: data || {},
			success: (res) => {
				// console.log("请求接口：", Url + "/api/front/" + url);
				// console.log("响应数据：", res.data);
				if (noVerify) {
					reslove(res.data, res);
				} else if (res.data.code == 200) reslove(res.data, res);
				else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
					toLogin();
					reject(res.data.message);
				} else if (res.data.code == 500) {
					reject(res.data.message || "系统异常");
				} else if (res.data.code == 400) {
					reject(res.data.message || "参数校验失败");
				} else if (res.data.code == 404) {
					reject(res.data.message || "没有找到相关数据");
				} else if (res.data.code == 403) {
					reject(res.data.message || "没有相关权限");
				} else reject(res.data.message || "系统错误");
			},
			fail: (msg) => {
				reject("请求失败");
			},
		});
	});
}

const request = {};

["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
	(method) => {
		request[method] = (api, data, opt, params) =>{
			return baseRequest(api, method, data, opt || {}, params);
		}
	}
);

const uploadFile = (url) => {
	return uni.uploadFile({
		url: Url + "/api/front/" + url,
		files: 图片地址对象数组,
		formData: {
			user: "test",
		},
		success: (res) => {
			console.log(res.data);
		},
	});
};

export { uploadFile };
export default request;
